import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/base/base_view_model.dart';
import '../../core/http/http_client.dart';
import '../../core/app_config.dart';
import '../../core/router/app_router.dart';
import '../user/user_model.dart';
import 'dart:convert';

class LoginViewModel extends BaseViewModel {
  final _httpClient = HttpClient();

  Future<void> login(String username, String password) async {
    try {
      setBusy(true);

      final response = await _httpClient.post('/admin/login', data: {
        'username': username,
        'password': password,
      });
      if (response.code == 200 && response.data != null) {
        final accessToken = response.data['access_token'];
        final refreshToken = response.data['refresh_token'];
        final adminData = response.data['admin'];
        // 将管理员数据转换为UserModel
        final userModel = UserModel.fromJson(adminData);
        final prefs = await SharedPreferences.getInstance();
        await _saveTokens(accessToken, refreshToken);
        await prefs.setString(AppConfig.userInfoKey, jsonEncode(userModel.toJson()));
        // ignore: use_build_context_synchronously
        GoRouter.of(AppRouter.router.routerDelegate.navigatorKey.currentContext!).go('/dashboard');
      } else {
        setError('登录失败，请检查用户名和密码', context: AppRouter.router.routerDelegate.navigatorKey.currentContext);
      }
    } catch (e) {
      setError('登录失败：${e.toString()}', context: AppRouter.router.routerDelegate.navigatorKey.currentContext);
    } finally {
      setBusy(false);
    }
  }

  Future<void> _saveTokens(String accessToken, String refreshToken) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(AppConfig.accessTokenKey, accessToken);
    await prefs.setString(AppConfig.refreshTokenKey, refreshToken);
  }
}
